/**
 * 
 */
package com.googolmo.NowPlaying.Receiver;

import com.googolmo.NowPlaying.Constant;
import com.googolmo.NowPlaying.Service.MusicService;
import com.googolmo.NowPlaying.SharePreferences.MusicPreferences;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

/**
 * @author user
 * 
 */
public class MusicReceiver extends BroadcastReceiver {

	Intent serverIntent;

	// MusicServer ms = new MusicServer();

	/**
	 * 
	 */
	public MusicReceiver() {
		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
	 * android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {

		try {
			if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
				Log.d("NowPlaying", intent.getAction());
				int state = intent.getIntExtra("state", 4);
				if (state == 0) {
					// 耳机拔出
					Log.d(Constant.TAG, "耳机拔出");
					try {
						serverIntent = new Intent(context, MusicService.class);
						// serverIntent.setAction(Constant.DELETE_NOTIFICATION);

						context.stopService(serverIntent);
						// MusicService.startService(context, serverIntent);
						// // context.startService(serverIntent);
						// if (MusicPreferences.getHandsetPlug(context) == 2) {
						// MusicService.stopService(MusicService.getInstance());
						// }

						MusicPreferences.setHandsetPlug(context, 0);
					} catch (Exception e) {
						Log.e("NowPlaying", "关闭失败");
					}

				} else if (state == 1) {
					// 耳机插入
					MusicPreferences.setHandsetPlug(context, 1);
				}
			} else if (intent.getAction().equals(Constant.PLAYBACK_COMPLETE)) {
				Log.d("NowPlaying", intent.getAction());
				MusicService.stopService(MusicService.getInstance());
			} else {
				Log.d(Constant.TAG, intent.getAction());
				Bundle bundle = intent.getExtras();
				serverIntent = new Intent(context, MusicService.getInstance()
						.getClass());
				serverIntent.putExtras(bundle);
				serverIntent.setAction(intent.getAction());
				MusicService.startService(context, serverIntent);
			}

		} catch (Exception e) {
			// Log.e(Constant.getTag, e.getMessage());
			// Toast.makeText(context, "Oops!something error!",
			// Toast.LENGTH_SHORT)
			// .show();
			// serverIntent = new Intent(context, ms.getClass());
			// serverIntent.setAction(Constant.DELETE_NOTIFICATION);
			// context.startService(serverIntent);
			e.printStackTrace();
		}

	}
}
